package com.eostoken.eos_wallet.ui.fragment;

import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.MapUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.eostoken.eos_wallet.R;
import com.eostoken.eos_wallet.base.BaseFragment;
import com.eostoken.eos_wallet.bean.IndexMarkIndexBean;
import com.eostoken.eos_wallet.bean.PageInfo;
import com.eostoken.eos_wallet.db.MgpWallet;
import com.eostoken.eos_wallet.mvp.mode.AppsModel;
import com.eostoken.eos_wallet.mvp.presenter.AppsPresenterImpl;
import com.eostoken.eos_wallet.mvp.view.AppsView;
import com.eostoken.eos_wallet.ui.adapter.MarkIndexAdapter;
import com.eostoken.eos_wallet.utils.Constants;
import com.eostoken.eos_wallet.utils.RSAUtils;
import com.eostoken.eos_wallet.utils.WalletUtils;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLayout;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullLoadMoreView;
import com.qmuiteam.qmui.widget.pullLayout.QMUIPullRefreshView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import static com.eostoken.eos_wallet.utils.Constants.INDEX_MARK;

public class MiningIndexFragment extends BaseFragment<AppsModel, AppsView, AppsPresenterImpl> implements AppsView {

    @BindView(R.id.topBar)
    QMUITopBar topBar;
    @BindView(R.id.numTv)
    AppCompatTextView numTv;
    @BindView(R.id.flayout)
    FrameLayout flayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshView)
    QMUIPullRefreshView refreshView;
    @BindView(R.id.loadMoreView)
    QMUIPullLoadMoreView loadMoreView;
    @BindView(R.id.pull_layout)
    QMUIPullLayout pullLayout;

    private int limit = 50;
    private String accountName;
    private MgpWallet wallet;
    private PageInfo pageInfo = new PageInfo();
    private QMUIPullLayout.PullAction mPullAction;
    private IndexMarkIndexBean indexMarkIndexBean;
    private MarkIndexAdapter markIndexAdapter;
    private List<IndexMarkIndexBean.DataBean.ListBean> markIndexItemList = new ArrayList<>();
    private String mNum = "0.00";

    @Override
    protected int getContentLayout() {
        return R.layout.fragment_mining_index;
    }

    @Override
    protected void initData() {
        wallet = WalletUtils.getCurrentWallet(getActivity());
        accountName = wallet.getCurrentAccountName();
    }

    @Override
    protected void initView(View contentView) {
        topBar.setTitle(getString(R.string.str_mining_index));
        topBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popOrFinish();
            }
        });

        markIndexAdapter = new MarkIndexAdapter(markIndexItemList);
        markIndexAdapter.setAnimationEnable(true);
        markIndexAdapter.setEmptyView(getEmptyView(R.mipmap.nofriend_groupchat, getString(R.string.str_no_empty_data), (ViewGroup) recyclerView.getParent()));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(markIndexAdapter);
        initLoadMore();
    }

    /**
     * 初始化加载更多
     */
    private void initLoadMore() {
        pullLayout.setActionListener(new QMUIPullLayout.ActionListener() {
            @Override
            public void onActionTriggered(@NonNull QMUIPullLayout.PullAction pullAction) {
                if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_TOP) {
                    // 这里的作用是防止下拉刷新的时候还可以上拉加载
                    markIndexAdapter.getLoadMoreModule().setEnableLoadMore(false);
                    pageInfo.reset();
                } else if (pullAction.getPullEdge() == QMUIPullLayout.PULL_EDGE_BOTTOM) {
                }
                getIndexMarkIndex();
                mPullAction = pullAction;
            }
        });

        markIndexAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                getIndexMarkIndex();
            }
        });
        markIndexAdapter.getLoadMoreModule().setAutoLoadMore(true);
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        markIndexAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }

    @Override
    public void updateView(Object data, int responseSuccessCode) {
        switch (responseSuccessCode) {
            case INDEX_MARK:
                if (mPullAction != null) {
                    pullLayout.finishActionRun(mPullAction);
                }
                if (data != null) {
                    indexMarkIndexBean = GsonUtils.fromJson(data.toString(), IndexMarkIndexBean.class);
                    if (indexMarkIndexBean != null) {
                        if (indexMarkIndexBean.getCode() == 0) {
                            IndexMarkIndexBean.DataBean dataBean = indexMarkIndexBean.getData();
                            if (dataBean != null) {
                                mNum = dataBean.getNum();
                                List<IndexMarkIndexBean.DataBean.ListBean> markIndexItems = dataBean.getList();
                                if (pageInfo.isFirstPage()) {
                                    numTv.setText(ObjectUtils.isEmpty(mNum) ? "0.00" : mNum);
                                    if (!ObjectUtils.isEmpty(markIndexItems)) {
                                        markIndexItemList.clear();
                                        markIndexItemList.addAll(markIndexItems);
                                    }
                                    markIndexAdapter.setList(markIndexItemList);
                                } else {
                                    if (!ObjectUtils.isEmpty(markIndexItems)) {
                                        markIndexItemList.addAll(markIndexItemList.size() - 1, markIndexItems);
                                    }
                                    markIndexAdapter.addData(markIndexItemList);
                                }

                            }
                        } else {
                            ToastUtils.showShort(indexMarkIndexBean.getMsg());
                        }
                    }
                }
                if (markIndexItemList.size() < limit) {
                    //如果不够一页,显示没有更多数据布局
                    markIndexAdapter.getLoadMoreModule().loadMoreEnd();
                } else {
                    markIndexAdapter.getLoadMoreModule().loadMoreComplete();
                }
                pageInfo.nextPage();
                break;
        }

    }

    @Override
    public void onFailure(Object data, int responseFailCode) {
        switch (responseFailCode) {
            case INDEX_MARK:
                if (mPullAction != null) {
                    pullLayout.finishActionRun(mPullAction);
                }
                markIndexAdapter.getLoadMoreModule().setEnableLoadMore(true);
                markIndexAdapter.getLoadMoreModule().loadMoreFail();
                break;
        }

    }

    @Override
    public void updateView(boolean success, Object o1, Object o2) {

    }

    @Override
    public AppsModel createModel() {
        return new AppsModel();
    }

    @Override
    public AppsView createView() {
        return this;
    }

    @Override
    public AppsPresenterImpl createPresenter() {
        return new AppsPresenterImpl(getActivity());
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void onResume() {
        super.onResume();
        //取消全屏设置
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        BarUtils.setStatusBarColor(getActivity(), ContextCompat.getColor(getActivity(), R.color.app_color_blue));
        getIndexMarkIndex();
    }

    @Override
    public void onStop() {
        super.onStop();
        pageInfo.reset();
    }

    private void getIndexMarkIndex() {
        try {
            Map params = MapUtils.newHashMap();
            params.put("address", accountName);
            params.put("limit", limit + "");
            params.put("page", pageInfo.page + "");
            String jsonData = GsonUtils.toJson(params);
            String content = RSAUtils.encrypt(jsonData);
            presenter.requestPortData(content, INDEX_MARK);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
